type Methods = 'GET' | 'POST' | 'DELETE' | 'PATCH'
// const BASE_URL = 'http://192.168.3.6:3000'
const BASE_URL = '/api'
import type { FetchOptions } from 'ofetch'
type SelfFetchOptions = (FetchOptions & {_autoLoading?: boolean,_mock?: string})
class Http {
  request<T = unknown>(url: string, method: Methods, data?: any, opts?: SelfFetchOptions){
    const jwt = localStorage.getItem('jwt')
    const route = useRoute()
    const router = useRouter()
    const defaultOpts = {
      method,
      baseURL: BASE_URL,
      onRequest({ options }) {
        if(jwt){
          options.headers = new Headers(options.headers)
          // options.headers.set('Authorization', `Bearer ${jwt}`)
          options.headers.set('Authorization', jwt)
        }
      },
      onRequestError() {
        showFailToast('请求出错，请重试！')
      },
      onResponseError({ response }) {
        const msg = response._data.statusMessage
        switch (response.status) {
          case 400:
            showFailToast(msg || '参数错误')
            break
          case 401:
            showLoadingToast({
              message: msg||'权限过期，请登录后继续操作...',
              forbidClick: true,
              duration: 0
            })
            setTimeout(() => {
              router.push(`/login?return_to=${route.fullPath}`)
              closeToast()
            }, 1500)
            break
          case 403:
            showFailToast(msg||'服务器拒绝访问')
            break
          case 404:
            showFailToast('请求地址错误')
            break
          case 500:
            showFailToast('服务器故障')
            break
          default:
            showFailToast('网络连接故障')
            break
        }
      },
    } as FetchOptions
    if (defaultOpts) {
      if (['POST','PATCH'].includes(method))
        defaultOpts.body = data
      else
        defaultOpts.params = data
    }
    return $fetch<T>(url, _merge(defaultOpts, opts))
  }
  get<T = any>(url: string, params?: any, options?: SelfFetchOptions) {
    return this.request<T>(url, "GET", params, options);
  }
  post<T = any>(url: string, data: any, options?: SelfFetchOptions) {
    return this.request<T>(url, "POST", data, options);
  }

  patch<T = any>(url: string, data: any, options?: SelfFetchOptions) {
    return this.request<T>(url, "PATCH", data, options);
  }

  delete<T = any>(url: string, params?: any, options?: SelfFetchOptions) {
    return this.request<T>(url, "DELETE", params, options);
  }
}

export const http = new Http()